//
//  MyMessageTabVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/11/1.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "MyMessageTabVC.h"
#import "MyMessageCell.h"
#import "MyMessageContentVC.h"
#import "MessageModel.h"
#import "MyMessageDefaultCell.h"
@interface MyMessageTabVC ()<MyMessageCellDelegate,MyMessageDefaultCellDelegate,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property(nonatomic,strong) NSMutableArray *msgMuta;
@property(nonatomic,assign) NSInteger pageSize;
@property(nonatomic,assign) NSInteger pageNumber;
@property(nonatomic,strong) MJRefreshAutoNormalFooter *footer;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSString *urlString;
@end
@implementation MyMessageTabVC
-(NSMutableArray *)msgMuta
{
    if (!_msgMuta) {
        _msgMuta = [NSMutableArray array];
    }
    return _msgMuta;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"消息中心";
    self.manager = [AFHTTPSessionManager manager];
    self.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadMore)];
    self.tableView.mj_footer = self.footer;
    [self.footer setTitle:[NSBundle bundleLocalizedStringForKey:@"footerTitle"]
            forState:MJRefreshStateNoMoreData];
    self.footer.stateLabel.font = [UIFont systemFontOfSize:12];
    self.footer.stateLabel.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1];
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectAllMessage:) name:@"selectAllMessage" object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(qingqiusibai:) name:@"qingqiusibai" object:nil];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.tableView.mj_header = header;
    [header beginRefreshing];
    
   
}
-(void)refresh
{
    self.pageSize = 10;
    self.pageNumber = 1;
    self.msgMuta = nil;
    if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]||[UserDefaultsHelper readAutoLogIn].length == 0) {
        [LogOutAccount presentOutAccount];
        [UIAlertViewWarningAccount showWarningAccount];
        [self.tableView.mj_header endRefreshing];
    }else {
        self.dict = @{
                      @"userId":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken]
                      };
        XLog(@"self.dict:%@",self.dict);
        self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            if (status == 200) {
                [self reloadInternetData];
            }else {
                [LogOutAccount presentOutAccount];
                [UIAlertViewWarningAccount showWarningAccount];
                [self.tableView.mj_header endRefreshing];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    }
    
    
}
-(void)reloadMore
{
    self.pageNumber ++;
    [self reloadInternetData];
    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
    [WSProgressHUD show];
    
}
-(void)reloadInternetData
{
    NSString *pageSizes = [NSString stringWithFormat:@"%ld",self.pageSize];
    NSString *pageNumbers = [NSString stringWithFormat:@"%ld",self.pageNumber];
    NSDictionary *dict = @{
                           @"pageSize":pageSizes,
                           @"pageNumber":pageNumbers,
                           @"uid":[UserDefaultsHelper readUid],
                           @"token":[UserDefaultsHelper readToken]
                           };
    XLog(@"dict:%@",dict);
    [CustomeManager POSTWithURLIndex:23 parameters:dict success:^(NSDictionary *dict) {
        
    } failure:^(NSError *error) {
        
    }];
}
-(void)qingqiusibai:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
    [self.tableView.mj_header endRefreshing];
    [WSProgressHUD dismiss];
}

-(void)selectAllMessage:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    NSArray *date = [dict objectForKey:@"date"];
    if (date.count) {
        for (NSDictionary *dict in date) {
            MessageModel *model = [MessageModel mj_objectWithKeyValues:dict];
            [self.msgMuta addObject:model];
        }
        if (date.count< 10) {
            self.footer.state = MJRefreshStateNoMoreData;
        }else {
            [self.tableView.mj_footer endRefreshing];
        }
    }
    if (self.msgMuta.count) {
        
        
    }else {
        [self.footer removeFromSuperview];
        self.tableView.emptyDataSetSource = self;
        self.tableView.emptyDataSetDelegate = self;
    }
    [self.tableView reloadData];
    [self.tableView.mj_header endRefreshing];
    [WSProgressHUD dismiss];
  
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.msgMuta.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    MessageModel *model = self.msgMuta[indexPath.section];
    if (model.icon.length >0) {
        MyMessageCell *cell = [MyMessageCell cellNibWithTableView:tableView];
        cell.delegate = self;
        cell.indexPath = indexPath;
        cell.model = model;
        return cell;
    }else {
        MyMessageDefaultCell *cell = [MyMessageDefaultCell cellNibWithTableView:tableView];
        cell.delegate = self;
        cell.indexPath = indexPath;
        cell.model = model;
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
     MessageModel *model = self.msgMuta[indexPath.section];
//    CGFloat cellHeight = [MCLabel getHeightWithTitle:model.content withFontSize:12];
    CGFloat cellHeight = [MCLabel getHeightByWidth:kUIScreen.size.width-32 title:model.content font:12];
    XLog(@"model.icon.length:%ld",model.icon.length);
    XLog(@"cellHeight:%f",cellHeight);
    if (model.icon.length>0) {
        return 185;
    }else {
        if (cellHeight >= 28) {
            return 185;
        }else {
            return 125;
        }
    }
}
- (void)myMessageDefaultCell:(MyMessageDefaultCell *)myMessageDefaultCell withClickBtn:(UIButton *)clickBtn withIndexPath:(nonnull NSIndexPath *)indexPath
{
    MyMessageContentVC *myMessageContentVC = [[MyMessageContentVC alloc]init];
    myMessageContentVC.msgModel = self.msgMuta[indexPath.section];
    [self.navigationController pushViewController:myMessageContentVC animated:YES];
}
- (void)myMessageCell:(MyMessageCell *)myMessageCell withClickBtn:(UIButton *)clickBtn withIndexPath:(nonnull NSIndexPath *)indexPath
{
    MyMessageContentVC *myMessageContentVC = [[MyMessageContentVC alloc]init];
    myMessageContentVC.msgModel = self.msgMuta[indexPath.section];
    [self.navigationController pushViewController:myMessageContentVC animated:YES];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MyMessageContentVC *myMessageContentVC = [[MyMessageContentVC alloc]init];
    MessageModel *model = self.msgMuta[indexPath.section];
    myMessageContentVC.msgModel = model;
    CGFloat cellHeight = [MCLabel getHeightByWidth:kUIScreen.size.width-32 title:model.content font:12];
    if (myMessageContentVC.msgModel.icon.length != 0) {
        [self.navigationController pushViewController:myMessageContentVC animated:YES];
    }else if (cellHeight >=28) {
         [self.navigationController pushViewController:myMessageContentVC animated:YES];
    }
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    UIImage *image = [UIImage imageNamed:@"empty"];
    return image;
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = [NSBundle bundleLocalizedStringForKey:@"noData"];
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont boldSystemFontOfSize:14],
                                 NSForegroundColorAttributeName:kLabel102Color
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}
@end
